package com.example.zsf.activity.account;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.example.zsf.R;
import com.example.zsf.activity.mine.UserAgreementActivity;
import com.example.zsf.base.ZSFInputBaseActivity;
import com.example.zsf.fragment.InputPhoneFragment;
import com.example.zsf.fragment.InputVerificationFragment;
import com.netease.nis.captcha.Captcha;
import com.netease.nis.captcha.CaptchaConfiguration;
import com.netease.nis.captcha.CaptchaListener;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends ZSFInputBaseActivity {

    @BindView(R.id.protocol_tv)
    TextView protocolTv;

    private Fragment currentFragment;
    private InputPhoneFragment inputPhoneFragment;
    private InputVerificationFragment inputVerificationFragment;
    private CaptchaConfiguration configuration;
    private String curPhoneNumber;
    private boolean isNeedJumpToVerificationFragment = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            getWindow().setAttributes(lp);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }


        ButterKnife.bind(this);
        initUI();
        initCaptcha();
    }


    private void initUI() {
        SpannableString spannableString = new SpannableString("《找搜服用户协议》");
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View view) {
                //jump to Protocol page
                Intent intent = new Intent(LoginActivity.this, UserAgreementActivity.class);
                startActivity(intent);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
            }
        }, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorBlue)), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        protocolTv.setText("注册即代表你同意");
        protocolTv.append(spannableString);
        protocolTv.setMovementMethod(LinkMovementMethod.getInstance());


        inputPhoneFragment = new InputPhoneFragment(new FetchVerificationCodeListener() {
            @Override
            public void fetchVerificationCode(String phoneNumber) {
                if (phoneNumber == null) {
                    return;
                }
                curPhoneNumber = phoneNumber;
                // 弹出验证码
                Captcha captcha = Captcha.getInstance().init(configuration);
                captcha.validate();
            }
        });

        currentFragment = inputPhoneFragment;
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.container, inputPhoneFragment);
        ft.show(inputPhoneFragment);
        ft.commit();
    }

    private void switchVerificationFragment(String validate) {
        inputVerificationFragment = new InputVerificationFragment(curPhoneNumber, validate, new FetchVerificationCodeListener() {
            @Override
            public void fetchVerificationCode(String phoneNumber) {
                // 弹出验证码
                Captcha captcha = Captcha.getInstance().init(configuration);
                captcha.validate();
            }
        });
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.container, inputVerificationFragment);
        ft.hide(inputPhoneFragment);
        ft.show(inputVerificationFragment);
        ft.commit();
    }

    private void initCaptcha() {

        configuration = new CaptchaConfiguration.Builder()
                .captchaId("cff4093947b8436d8fcf0c41aef44508")// 验证码业务id
                .mode(CaptchaConfiguration.ModeType.MODE_CAPTCHA)
                .listener(new CaptchaListener() {
                    @Override
                    public void onReady() {

                    }

                    @Override
                    public void onValidate(String s, String s1, String s2) {
                        if (Boolean.parseBoolean(s)) {
                            if (isNeedJumpToVerificationFragment) {
                                isNeedJumpToVerificationFragment = false;
                                switchVerificationFragment(s1);
                            } else {
                                protocolTv.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        inputVerificationFragment.verifySuccess(s1);
                                    }
                                });
                            }
                        }
                    }

                    @Override
                    public void onError(int i, String s) {

                    }

                    @Override
                    public void onCancel() {

                    }

                    @Override
                    public void onClose() {

                    }
                }) // 验证码回调监听器
                .timeout(1000 * 10) // 超时时间，一般无需设置
                .useDefaultFallback(true) // 是否使用默认降级方案，默认开启
                .hideCloseButton(false)//是否隐藏右上角关闭按钮，默认不隐藏
                .build(this);
    }


    @OnClick(R.id.protocol_tv)
    public void onViewClicked(View view) {
    }


    public interface FetchVerificationCodeListener {
        void fetchVerificationCode(String phoneNumber);
    }
}